﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;

namespace StringUtils {

  public class StringValueAttribute : Attribute {
    private string stringValue;
    public string StringValue {
      get { return stringValue; }
    }
    public StringValueAttribute( string value ) {
      this.stringValue = value;
    }
  }

  public class EnumUtils {
    public static string GetStringValue( Enum value ) {
      FieldInfo fieldInfo = value.GetType( ).GetField( value.ToString( ) );
      StringValueAttribute[ ] attributes = ( StringValueAttribute[ ] ) fieldInfo.GetCustomAttributes( typeof( StringValueAttribute ), false );
      if ( attributes.Length > 0 ) {
        return attributes[ 0 ].StringValue;
      } else {
        return value.ToString( );
      }
    }

    public static object GetEnumValue( string value, Type enumType ) {
      string[ ] names = Enum.GetNames( enumType );
      foreach ( string name in names ) {
        if ( GetStringValue( ( Enum ) Enum.Parse( enumType, name ) ).Equals( value ) ) {
          return Enum.Parse( enumType, name );
        }
      }

      throw new ArgumentException( "The string is not a description or value of the specified enum." );
    }
  }


}
